#
# File: handlers.py
# Description: Main django views for accounts app
#
# Copyright 2013 Adam Meadows
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
#

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import Http404
from django.utils.translation import ugettext as _
from django.shortcuts import render, redirect

from common.handler_model import RequestHandler

#
# Handler definitions
#
class HomeHandler(RequestHandler):
    template = 'accounts/templates/home.tmpl'
    ERROR_COOKIE = 'error_msg'

    def __init__(self, request):
        super(self.__class__, self).__init__(request)
        if not self.request.user.is_authenticated():
            self.template = 'accounts/templates/anon-home.tmpl'
            error_msg = self.request.COOKIES.get(self.ERROR_COOKIE, '')
            self.template_kwargs[self.ERROR_COOKIE] = error_msg

    def get(self):
        response = self.render_template()
        if not self.request.user.is_authenticated():
            response.delete_cookie(self.ERROR_COOKIE)
        return response

class SignUpHandler(RequestHandler):
    template = 'accounts/templates/anon-signup.tmpl'

    def get(self):
        return self.render_template()

    def post(self):
        # TODO: Verify params
        email = request.POST.get('email', '')
        first = request.POST.get('first', '')
        last = request.POST.get('last', '')
        password = request.POST.get('password', '')
        user = User.objects.create_user(username=email, email=email)
        user.set_password(password)
        user.first_name = first
        user.last_name = last
        user.save()

        # TODO: redirec to a success page
        return redirect('/')

class SignInHandler(RequestHandler):

    def _error(self, response, message):
        response.set_cookie(HomeHandler.ERROR_COOKIE, message)

    def get(self):
        # There is no get for sign-in, just a form submission handler
        raise Http404

    def post(self):
        username = self.request.POST.get('username', '')
        password = self.request.POST.get('password', '')
        user = authenticate(username=username, password=password)
        response = redirect('/')

        if user is None:
            self._error(response, _('Invalid Email/Password'))
        elif not user.is_active:
            self._error(response, _('Account Disabled'))
        else:
            login(self.request, user)

        return response

